#!/usr/bin/env python
# -*- coding:utf-8 -*-

from app import db
import math
import json
from sqlalchemy import or_

from models.commentInfoModel import CommentInfo
from utils import commons
from utils.response_code import RET, error_map_EN
from utils.loggings import loggings


class CommentInfoController(CommentInfo):

    # add
    @classmethod
    def add(cls, **kwargs):
        
        try:
            model = CommentInfo(
                CommentPostID=kwargs.get('CommentPostID'),
                CommentUserID=kwargs.get('CommentUserID'),
                CommentContent=kwargs.get('CommentContent'),
                CommentParent=kwargs.get('CommentParent'),
                CommentRoot=kwargs.get('CommentRoot'),
                IsRead=kwargs.get('IsRead'),
                CreateTime=kwargs.get('CreateTime'),
                ModifyTime=kwargs.get('ModifyTime'),
                
            )
            db.session.add(model)
            db.session.commit()
            results = commons.query_to_dict(model)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    # get
    @classmethod
    def get(cls, **kwargs):
        try:
            filter_list = [cls.IsDelete == 0]
            if kwargs.get('AutoID'):
                filter_list.append(cls.AutoID == kwargs.get('AutoID'))
            else:
                if kwargs.get('CommentPostID') is not None:
                    filter_list.append(cls.CommentPostID == kwargs.get('CommentPostID'))
                if kwargs.get('CommentUserID'):
                    filter_list.append(cls.CommentUserID == kwargs.get('CommentUserID'))
                if kwargs.get('CommentContent'):
                    filter_list.append(cls.CommentContent == kwargs.get('CommentContent'))
                if kwargs.get('CommentParent') is not None:
                    filter_list.append(cls.CommentParent == kwargs.get('CommentParent'))
                if kwargs.get('CommentRoot') is not None:
                    filter_list.append(cls.CommentParent == kwargs.get('CommentRoot'))
                if kwargs.get('IsRead'):
                    filter_list.append(cls.IsRead == kwargs.get('IsRead'))
                if kwargs.get('CreateTime'):
                    filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))
                if kwargs.get('ModifyTime'):
                    filter_list.append(cls.ModifyTime == kwargs.get('ModifyTime'))
                
            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))
            
            comment_info_info = db.session.query(cls).filter(*filter_list)
            
            count = comment_info_info.count()
            pages = math.ceil(count / size)
            comment_info_info = comment_info_info.limit(size).offset((page - 1) * size).all()

            # judge whether the data is None
            if not comment_info_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No query results'}
                
            results = commons.query_to_dict(comment_info_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages, 'data': results}
            
        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    # delete
    @classmethod
    def delete(cls, **kwargs):
        try:
            filter_list = [cls.IsDelete == 0]
            if kwargs.get('AutoID'):
                primary_key_list = []
                for primary_key in str(kwargs.get('AutoID')).replace(' ', '').split(','):
                    primary_key_list.append(cls.AutoID == primary_key)
                filter_list.append(or_(*primary_key_list))
                
            else:
                if kwargs.get('CommentPostID') is not None:
                    filter_list.append(cls.CommentPostID == kwargs.get('CommentPostID'))
                if kwargs.get('CommentUserID'):
                    filter_list.append(cls.CommentUserID == kwargs.get('CommentUserID'))
                if kwargs.get('CommentContent'):
                    filter_list.append(cls.CommentContent == kwargs.get('CommentContent'))
                if kwargs.get('CommentParent') is not None:
                    filter_list.append(cls.CommentParent == kwargs.get('CommentParent'))
                if kwargs.get('CommentRoot') is not None:
                    filter_list.append(cls.CommentParent == kwargs.get('CommentRoot'))
                if kwargs.get('CreateTime'):
                    filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))
                if kwargs.get('ModifyTime'):
                    filter_list.append(cls.ModifyTime == kwargs.get('ModifyTime'))
                
            res = db.session.query(cls).filter(*filter_list).with_for_update().update({'IsDelete': 1})
            if res < 1:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to delete'}
                
            db.session.commit()
            return {'code': RET.OK, 'message': error_map_EN[RET.OK]}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    # update
    @classmethod
    def update(cls, **kwargs):
        try:
            
            res = db.session.query(cls).filter(
                cls.AutoID == kwargs.get('AutoID'),
                cls.IsDelete == 0
            ).with_for_update().update(kwargs)
            
            if res < 1:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}
            db.session.commit()
            
            return {'code': RET.OK, 'message': error_map_EN[RET.OK]}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    # batch add
    @classmethod
    def add_list(cls, **kwargs):
        param_list = json.loads(kwargs.get('CommentInfoList'))
        model_list = []
        for param_dict in param_list:
            
            model = CommentInfo(
                CommentPostID=param_dict.get('CommentPostID'),
                CommentUserID=param_dict.get('CommentUserID'),
                CommentContent=param_dict.get('CommentContent'),
                CommentParent=param_dict.get('CommentParent'),
                CommentRoot=kwargs.get('CommentRoot'),
                IsRead=kwargs.get('IsRead'),
                CreateTime=param_dict.get('CreateTime'),
                ModifyTime=param_dict.get('ModifyTime'),
                
            )
            model_list.append(model)
        
        try:
            db.session.add_all(model_list)
            db.session.commit()
            results = []
            for model in model_list:
                results.append(commons.query_to_dict(model))
            
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()
